/**
 * 壁纸详情页逻辑
 */
document.addEventListener('DOMContentLoaded', () => {
    // DOM元素
    const elements = {
        wallpaperDetail: document.getElementById('wallpaper-detail'),
        wallpaperInfo: document.getElementById('wallpaper-info'),
        backBtn: document.getElementById('back-btn'),
        favoriteBtn: document.getElementById('favorite-btn'),
        downloadBtn: document.getElementById('download-btn'),
        wallpaperTitle: document.getElementById('wallpaper-title'),
        wallpaperDescription: document.getElementById('wallpaper-description'),
        wallpaperCategory: document.getElementById('wallpaper-category'),
        wallpaperResolution: document.getElementById('wallpaper-resolution'),
        wallpaperDownloads: document.getElementById('wallpaper-downloads'),
        wallpaperTags: document.getElementById('wallpaper-tags'),
        relatedWallpapers: document.getElementById('related-wallpapers')
    };
    
    // 状态
    const state = {
        wallpaper: null,
        isFavorite: false
    };
    
    /**
     * 初始化详情页
     */
    async function init() {
        // 获取壁纸ID
        const urlParams = new URLSearchParams(window.location.search);
        const wallpaperId = urlParams.get('id');
        
        if (!wallpaperId) {
            showError('缺少壁纸ID参数');
            return;
        }
        
        // 绑定事件
        bindEvents();
        
        // 加载壁纸详情
        await loadWallpaperDetail(wallpaperId);
    }
    
    /**
     * 绑定事件处理
     */
    function bindEvents() {
        // 返回按钮点击
        elements.backBtn.addEventListener('click', () => {
            // 检查是否有历史记录，有则返回，没有则回到首页
            if (window.history.length > 1) {
                window.history.back();
            } else {
                window.location.href = 'index.html';
            }
        });
        
        // 收藏按钮点击
        elements.favoriteBtn.addEventListener('click', toggleFavorite);
        
        // 下载按钮点击
        elements.downloadBtn.addEventListener('click', downloadWallpaper);
    }
    
    /**
     * 加载壁纸详情
     */
    async function loadWallpaperDetail(wallpaperId) {
        try {
            // 获取壁纸详情
            const response = await API.getWallpaperDetail(wallpaperId);
            state.wallpaper = response.data;
            
            // 检查是否已收藏
            const favoriteResponse = await API.checkFavorite(wallpaperId);
            state.isFavorite = favoriteResponse.is_favorite;
            
            // 渲染壁纸详情
            renderWallpaperDetail();
            
            // 更新收藏按钮状态
            updateFavoriteButton();
            
        } catch (error) {
            console.error('加载壁纸详情失败:', error);
            showError('加载壁纸详情失败，请刷新重试');
        }
    }
    
    /**
     * 渲染壁纸详情
     */
    function renderWallpaperDetail() {
        const { wallpaper } = state;
        
        // 渲染壁纸图片
        elements.wallpaperDetail.innerHTML = `
            <img src="${API.getWallpaperImageUrl(wallpaper.id)}" alt="${wallpaper.title}">
        `;
        
        // 显示壁纸信息
        elements.wallpaperInfo.classList.remove('hidden');
        
        // 标题使用分类名称
        elements.wallpaperTitle.textContent = wallpaper.title;
        
        // 壁纸描述
        elements.wallpaperDescription.textContent = wallpaper.description || '暂无描述';
        
        // 基本信息
        elements.wallpaperCategory.textContent = getCategoryName(wallpaper.categoryId);
        elements.wallpaperResolution.textContent = `${wallpaper.width} x ${wallpaper.height}`;
        elements.wallpaperDownloads.textContent = formatNumber(wallpaper.downloads);
        
        // 渲染标签
        renderTags(wallpaper.tags);
        
        // 渲染相关壁纸
        if (wallpaper.relatedWallpapers && wallpaper.relatedWallpapers.length > 0) {
            renderRelatedWallpapers(wallpaper.relatedWallpapers);
        } else {
            document.querySelector('.related-section').classList.add('hidden');
        }
        
        // 添加到最近查看
        Storage.addRecentlyViewed(wallpaper.id);
    }
    
    /**
     * 渲染标签
     */
    function renderTags(tags) {
        if (!tags || tags.length === 0) {
            document.querySelector('.tags-section').classList.add('hidden');
            return;
        }
        
        elements.wallpaperTags.innerHTML = '';
        tags.forEach(tag => {
            const tagElement = document.createElement('div');
            tagElement.className = 'tag';
            tagElement.textContent = tag;
            elements.wallpaperTags.appendChild(tagElement);
        });
    }
    
    /**
     * 渲染相关壁纸
     */
    function renderRelatedWallpapers(relatedWallpapers) {
        elements.relatedWallpapers.innerHTML = '';
        debugger
        relatedWallpapers.forEach(wallpaper => {
            const relatedCard = document.createElement('div');
            relatedCard.className = 'related-card';
            relatedCard.innerHTML = `
                <img src="${API.getWallpaperThumbnailUrl(wallpaper.id)}" alt="${wallpaper.title}">
            `;

            // 点击跳转到相关壁纸详情
            relatedCard.addEventListener('click', () => {
                window.location.href = `detail.html?id=${wallpaper.id}`;
            });
            
            elements.relatedWallpapers.appendChild(relatedCard);
        });
    }
    
    /**
     * 更新收藏按钮状态
     */
    function updateFavoriteButton() {
        if (state.isFavorite) {
            elements.favoriteBtn.classList.add('active');
            elements.favoriteBtn.innerHTML = '<img src="icon/favorite-s-fill.svg" alt="图标" width="24" height="24">';
        } else {
            elements.favoriteBtn.classList.remove('active');
            elements.favoriteBtn.innerHTML = '<img src="icon/favorite-s-line.svg" alt="图标" width="24" height="24">';
        }
    }
    
    /**
     * 切换收藏状态
     */
    async function toggleFavorite() {
        if (!state.wallpaper) return;
        
        try {
            if (state.isFavorite) {
                // 取消收藏
                await API.removeFromFavorites(state.wallpaper.id);
                state.isFavorite = false;
            } else {
                // 添加收藏
                await API.addToFavorites(state.wallpaper.id);
                state.isFavorite = true;
            }
            
            // 更新按钮状态
            updateFavoriteButton();
            
            // 显示反馈
            showToast(state.isFavorite ? '已添加到收藏' : '已从收藏中移除');
            
        } catch (error) {
            console.error('操作收藏失败:', error);
            showToast('操作失败，请重试');
        }
    }
    
    /**
     * 下载壁纸
     */
    async function downloadWallpaper() {
        if (!state.wallpaper) return;
        
        try {
            // 显示下载中状态
            elements.downloadBtn.innerHTML = '<img src="icon/loading.svg" alt="图标" width="42" height="42">';
            elements.downloadBtn.disabled = true;
            
            // 获取下载信息
            const download_url = await API.getWallpaperDownloadUrl(state.wallpaper.id);

            // 创建一个隐藏的a标签并触发下载
            const downloadLink = document.createElement('a');
            downloadLink.href = download_url;
            downloadLink.download = `wallpaper-${state.wallpaper.id}.jpg`;
            document.body.appendChild(downloadLink);
            downloadLink.click();
            document.body.removeChild(downloadLink);
            
            // 恢复按钮状态
            elements.downloadBtn.innerHTML = '<img src="icon/download-s.svg" alt="图标" width="24" height="24">';
            elements.downloadBtn.disabled = false;
            
            // 显示反馈
            showToast('壁纸开始下载');
            
        } catch (error) {
            console.error('下载壁纸失败:', error);
            showToast('下载失败，请重试');
            
            // 恢复按钮状态
            elements.downloadBtn.innerHTML = '<img src="icon/download-s.svg" alt="图标" width="24" height="24">';
            elements.downloadBtn.disabled = false;
        }
    }
    
    /**
     * 显示错误信息
     */
    function showError(message) {
        elements.wallpaperDetail.innerHTML = `
            <div class="error-message">
                <i class="ri-error-warning-line"></i>
                <p>${message}</p>
                <button class="btn" onclick="window.location.href='index.html'">返回首页</button>
            </div>
        `;
    }
    
    /**
     * 显示反馈提示
     */
    function showToast(message) {
        // 创建提示元素
        const toast = document.createElement('div');
        toast.className = 'toast';
        toast.textContent = message;
        
        // 添加到页面
        document.body.appendChild(toast);
        
        // 触发动画
        setTimeout(() => {
            toast.classList.add('show');
        }, 10);
        
        // 自动移除
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => {
                document.body.removeChild(toast);
            }, 300);
        }, 2000);
    }
    
    /**
     * 格式化数字为带千分位的字符串
     */
    function formatNumber(num) {
        return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
    
    /**
     * 根据分类ID获取分类名称
     */
    function getCategoryName(categoryId) {
        const categoryMap = {
            'nature': '自然风光',
            'city': '城市建筑',
            'abstract': '抽象艺术',
            'minimal': '简约风格',
            'dark': '暗色系',
            'bright': '亮色系'
        };
        
        return categoryMap[categoryId] || categoryId;
    }
    
    // 初始化
    init();
}); 